//
//  ViewController.swift
//  09ImageScroll
//
//  Created by Clover on 2018/4/17.
//  Copyright © 2018年 youbing. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var scrollview: UIScrollView!
    @IBOutlet weak var imageView: UIImageView!

    @IBOutlet weak var image_top: NSLayoutConstraint!
    @IBOutlet weak var image_left: NSLayoutConstraint!
    @IBOutlet weak var image_bottom: NSLayoutConstraint!
    @IBOutlet weak var image_right: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        scrollview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }
  
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.updateMinZoomScaleForSize(view.bounds.size)
    }
    
    func updateMinZoomScaleForSize(_ size : CGSize) {
        let widthScale = size.width / imageView.bounds.width
        let heightScale = size.height / imageView.bounds.height
        let minScale = min(widthScale,heightScale)
        
        scrollview.minimumZoomScale = minScale;
        scrollview.maximumZoomScale = 3.0;
        scrollview.zoomScale = minScale;
    }
    
    fileprivate func updateConstraintsForSize(_ size: CGSize) {
        let yOffset = max(0, (size.height - imageView.frame.height) / 2)
        image_top.constant = yOffset
        image_bottom.constant = yOffset
        
        ////根据宽度计算imageView前后约束的偏移量
        let xOffset = max(0, (size.width - imageView.frame.width) / 2)
        image_left.constant = xOffset
        image_right.constant = xOffset
        
        view.layoutIfNeeded()
    }
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    public func scrollViewDidZoom(_ scrollView: UIScrollView) {
       updateConstraintsForSize(view.bounds.size)
    }
    
}

extension UIViewController : UIScrollViewDelegate{
    
}

